package com.zee.home.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.common.exception.ExceptionCast;
import com.zee.common.model.response.CommonCode;
import com.zee.common.utils.AssertUtil;
import com.zee.common.utils.TimeConvertUtil;
import com.zee.home.dao.UserDao;
import com.zee.home.entity.User;
import com.zee.home.entity.UserToken;
import com.zee.home.model.dto.LoginDTO;
import com.zee.home.service.IUserService;
import com.zee.home.service.IUserTokenService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {
    @Autowired
    private IUserTokenService tokenService;
    @Autowired
    private UserDao userDao;

    @Override
    public User getByMobile(String mobile) {
        return userDao.getUserByMobile(mobile);
    }

    @Override
    public User getUserByUserId(Integer userId) {
        return baseMapper.getUserByUserId(userId);
    }

    @Override
    public Map<String, Object> login(LoginDTO dto) {
        User user = getByMobile(dto.getMobile());
        AssertUtil.isNull(user, CommonCode.ACCOUNT_PASSWORD_ERROR);

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(dto.getPassword()))) {
            ExceptionCast.cast(CommonCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取登录token
        UserToken userToken = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", userToken.getToken());
        map.put("expire", TimeConvertUtil.getMillisTime(userToken.getExpireTime()) - System.currentTimeMillis());
        map.put("createTime", LocalDateTimeUtil.formatNormal(userToken.getCreateTime()));
        map.put("expireTime", LocalDateTimeUtil.formatNormal(userToken.getExpireTime()));

        return map;
    }

}